﻿using System;

namespace Eflong.Monitor
{
    /// <summary>
    /// 统计值类
    /// </summary>
    public class StatValue
    {
        public StatValue( )
        {
            first = true;
            time = DateTime.Now;
            tmMax = time;
            tmMin = time;
        }

        public void Init( float v )
        {
            first = false;
            v0 = v1 = v;
            avg = vmax = vmin = v;
            sum = v;
            count = 1;
            tmMax = tmMin = time = DateTime.Now;
        }

        public void Changing( float v )
        {
            if ( first )
            {
                Init( v );
            }
            else
            {
                if ( vmax < v )
                {
                    vmax = v;
                    tmMax = DateTime.Now;
                }
                if ( vmin > v )
                {
                    vmin = v;
                    tmMin = DateTime.Now;
                }

                v1 = v;
                sum += v;
                count++;
                avg = ( float )( ( int )( sum / count * 100 ) ) / 100;
            }
        }

        public StatValue Clone( )
        {
            if ( !this.first )
            {
                StatValue item = ( StatValue )this.MemberwiseClone( );
                return item;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 重新初始化
        /// </summary>
        public void ReInit( float v )
        {
            sum = avg;
            count = 1;
            time = DateTime.Now;
            vmax = v;
            vmin = v;
            v0 = v1 = v;
            tmMax = time;
            tmMin = time;
        }

        private bool first;

        /// <summary>
        /// 时刻
        /// </summary>
        public DateTime time;

        /// <summary>
        /// 平均值
        /// </summary>
        public float avg;

        /// <summary>
        /// 最大值
        /// </summary>
        public float vmax;

        /// <summary>
        /// 最小值
        /// </summary>
        public float vmin;

        /// <summary>
        /// 最大值时刻
        /// </summary>
        public DateTime tmMax;

        /// <summary>
        /// 最小值时刻
        /// </summary>
        public DateTime tmMin;

        /// <summary>
        /// 初始值
        /// </summary>
        public float v0;

        /// <summary>
        /// 结束值
        /// </summary>
        public float v1;

        /// <summary>
        /// 统计之和
        /// </summary>
        private float sum;

        /// <summary>
        /// 计数
        /// </summary>
        private int count;
    }
}